package com.lry.basic.thread;

import java.util.concurrent.*;

public class FutureTest {

    static Executor executor = Executors.newFixedThreadPool(5);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        saveOrder();
    }

    //Supplier（供应者，无参有返回值）,Function（有参有返回值，类似map函数）
    // Consumer（消费者，有参无返回值）,Predicate(预测者，根据参数返回boolean)

    //thenApply: 接收上一个的返回值，自己也可以返回
    //thenAccept: 接收上一个返回值，自己无返回值
    //thenRun: 执行，无参无返回值
    //thenCompose：接收上一个的返回值，自己也可以返回，CompletableFuture.supplyAsync
    //thenCombine：接收前面两个异步任务的结果，执行，有返回值
    //thenAcceptBoth:接收前面两个异步任务的结果，执行，无返回值

    public static void saveOrder() throws ExecutionException, InterruptedException {

        CompletableFuture<String> userFuture = CompletableFuture.supplyAsync(()->{

            return "1";

        },executor).thenRun(()->{

        }).thenAcceptAsync(userId->{

            System.out.println(userId);

        }).thenApplyAsync(userId -> {

            return "2";

        },executor).thenComposeAsync(userId -> CompletableFuture.supplyAsync(()->{
            System.out.println(userId);
            return "3";

        }),executor).thenCombineAsync(CompletableFuture.supplyAsync(()->{

            return "4";

        },executor),(s,s1)->{

            return "5";

        }).exceptionally(throwable -> {
            return null;
        }).handleAsync((str,throwable)->{
            //没有异常也会执行
            return null;
        },executor);

        System.out.println(userFuture.get());

    }
}
